//
//  main.c
//  03、整型有序数组二分查找
//
//  Created by blovejin on 2023/12/25.
//

#include <stdio.h>

int binary_search(int a[], int k, int s)
{
    int left = 0;
    int right = s - 1;
    
    while (left <= right)
    {
        int mid = (left + right) / 2;
        if (a[mid] > k)
        {
            right = mid - 1;
        }
        else if (a[mid] < k)
        {
            left = mid + 1;
        }
        else
        {
            return mid;
        }
    }
    
    return -1;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int key = 7;
    // 找到了，返回找到位置的下标
    // 找不到，返回-1
    int sz = sizeof(arr) / sizeof(arr[0]);
    int ret = binary_search(arr, key, sz);
    if (-1 == ret)
    {
        printf("找不到\n");
    }
    else
    {
        printf("找到了，下标是：%d\n", ret);
    }
    return 0;
}
